<template>
  <transition enter-active-class="slideInUp faster animated" leave-active-class="slideOutDown faster animated">
    <div class="chooseSongModule" v-show="isShowAni">
      <div class="chooseSongBox publicVCenter">
        <!-- 头部和关闭按钮 -->
        <img src="@/assets/image/popupArea/closeIcon.png" class="closeIcon" v-tap="{ methods: closePopupModule }" />
        <div v-if="musicMode === '1'" class="singer-name-wrapper">
          {{ selectedSingerName || '未知歌手' }}
        </div>
        <img v-else src="@/assets/image/popupArea/chooseSongTitle.png" class="chooseSongTitle" />
        <!-- 歌手模式：仅在 musicMode === '1' 时显示歌手轮播与歌手名 -->
        <!-- <template v-if="musicMode === '1'">
          START: 修改歌手轮播区域
          <div class="singer-carousel-container">
            左导航箭头 (增加 is-disabled 类绑定)
            <div class="arrow left-arrow" :class="{ 'is-disabled': singerList.length <= 1 }" v-tap="{ methods: navigate, direction: -1 }"></div>
            <div class="singer-carousel-wrapper">
              <div class="singer-carousel" ref="singerCarousel">
                歌手卡片项
                <div
                  class="singer-item"
                  v-for="singer in singerList"
                  :key="singer.awardid"
                  v-tap="{ methods: handleSelectSinger, singerId: singer.awardid }"
                >
                  <img :src="singer.avator" class="singer-image" />
                  <img v-if="currentSingerId === singer.awardid" src="@/assets/image/popupArea/tickIcon.png" class="tick-icon" />
                </div>
              </div>
            </div>
            右导航箭头 (增加 is-disabled 类绑定)
            <div class="arrow right-arrow" :class="{ 'is-disabled': singerList.length <= 1 }" v-tap="{ methods: navigate, direction: 1 }"></div>
          </div>
          分页器 (小圆点)
          <div class="pagination-dots">
            <span
              v-for="(singer, index) in singerList"
              :key="singer.awardid"
              class="dot"
              :class="{ active: currentSingerIndex === index }"
            ></span>
          </div>
          歌手介绍 (名字)
          <div class="singer-intro-box">
            <div class="singer-intro">{{ selectedSingerName }}</div>
          </div>
          END: 修改歌手轮播区域
        </template> -->
        <!-- 导航栏 -->
        <div class="nav publicVCenter">
          <div class="navItem publicVCenter" :class="{ active: navIndex === 0 }" v-tap="{ methods: chooseNav, navIndex: 0 }">歌曲列表</div>
          <div class="navItem publicVCenter" :class="{ active: navIndex === 1 }" v-tap="{ methods: chooseNav, navIndex: 1 }">
            已点({{ orderedNum }}首)
          </div>
        </div>
        <!-- nav0：歌曲列表 -->
        <div class="songSheetWrap" v-if="navIndex === 0">
          <div
            class="songItem publicVCenter"
            v-for="item in songSheetList"
            :key="item.id"
            v-tap="{ methods: handleChooseSong, song: item }"
          >
            <div class="info">
              <div class="songName">{{ item.name }}</div>
              <div class="chooseNum">{{ item.times }}人点过</div>
            </div>
            <div class="price">{{ item.price }}元</div>
          </div>
        </div>
        <!-- nav1：已点列表（保持不变） -->
        <div class="playSheetWrap" v-if="navIndex === 1">
          <div class="songItem publicVCenter" v-for="(item, index) in songOrderList" :key="index">
            <div class="songName">{{ item.name }}</div>
            <div class="userInfo publicVCenter">
              <img :src="item.avator" class="headImg" />
              <div class="userName">{{ item.wxName }}</div>
            </div>
          </div>
        </div>
      </div>
      <!-- 点歌确认弹窗 (保持不变) -->
      <div v-if="isConfirmModalVisible" class="order-confirm-dialog-wrap publicHvCenter">
        <div class="shade" v-tap="{ methods: closeModal }" />
        <div class="dialog-content publicVCenter">
          <div class="dialog-title">点歌送祝福</div>
          <div class="form-item">
            <div class="form-key">您的桌号？</div>
            <div class="form-val">
              <input
                v-model="form.deskNum"
                class="dialog-input"
                type="text"
                placeholder="请输入桌号"
              />
            </div>
          </div>
          <div class="form-item">
            <div class="form-key">送一句祝福吧</div>
            <div class="form-val bless-container">
              <textarea
                v-model="form.blessing"
                class="bless-txtarea"
                :maxlength="canCustomizeInput ? 20 : 0"
                type="text"
                placeholder="请填写祝福语（20字）"
              />
              <div v-tap="{ methods: getTmpBless }" class="yulu-btn">语录</div>
            </div>
          </div>
          <div v-tap="{ methods: confirmAndPay }" class="pay-btn publicHvCenter">支付 ¥{{ songToOrder.price }} 点歌送祝福</div>
          <div v-tap="{ methods: closeModal }" class="cancel-btn">
            取消
          </div>
        </div>
      </div>
    </div>
  </transition>
</template>
<script>
import { mapMutations, mapState } from 'vuex';
import { POPUP_MODULE } from '@/assets/constant/index';
import { getSongOrderedList, getSongSheetList } from '@/api/music/index';
import { timeoutTask } from '../../utils';

const wx = require('weixin-js-sdk');
// 简单祝福语列表，用于“语录”功能
const BLESSING_LIST = ['everybody high 起来！', '为友情干杯！', '今夜不醉不归！', '我有酒，你有故事吗?', '希望你点的歌，我也会唱。'];
export default {
  name: 'chooseSongPopup',
  computed: {
    ...mapState({
      musicMode: (state) => state.app.musicMode,
      songSheetList: (state) => state.app.songSheetList,
      songOrderList: (state) => state.app.songOrderList,
      singerList: (state) => state.app.singerList,
      currentSingerId: (state) => state.app.currentSingerId,
      canCustomizeInput: (state) => state.app.canCustomizeInput,
    }),
    selectedSingerName() {
      if (this.musicMode === '0' || !this.currentSingerId) {
        return '';
      }
      const singer = this.singerList.find((s) => s.awardid === this.currentSingerId);
      return singer ? singer.name : '';
    },
    orderedNum() {
      return this.songOrderList.length;
    },
    // START: 新增计算属性，用于获取当前选中歌手的索引
    currentSingerIndex() {
      if (!this.currentSingerId || this.singerList.length === 0) return -1;
      return this.singerList.findIndex((s) => s.awardid === this.currentSingerId);
    },
    // END: 新增计算属性
  },
  // START: 新增 watch，监听选中歌手变化并自动滚动到对应位置
  watch: {
    currentSingerIndex(newIndex) {
      if (newIndex !== -1) {
        this.$nextTick(() => {
          this.scrollToSinger(newIndex);
        });
      }
    },
    canCustomizeInput(value) {
      if (!value) {
        this.form.blessing = '';
      }
    },
    // 监听弹窗显示状态，每次打开时刷新数据
    isShowAni(newVal) {
      if (newVal) {
        this.fetchInitialData();
      }
    },
  },
  // END: 新增 watch
  created() {},
  mounted() {
    // 执行弹出动画
    this.showAniStart();
  },
  data() {
    return {
      isShowAni: false, // chooseSong box弹出动画
      chooseSongModuleKey: POPUP_MODULE.chooseSongModule.key,
      chooseSingerModuleKey: POPUP_MODULE.chooseSingerModule.key,
      navIndex: 0,
      isConfirmModalVisible: false,
      songToOrder: null,
      form: {
        deskNum: '',
        blessing: '',
      },
    };
  },
  methods: {
    ...mapMutations({
      togglePopup: 'app/togglePopup',
      setOrigin: 'app/setOrigin',
      setMusicMode: 'app/setMusicMode',
      setSingerList: 'app/setSingerList',
      setCurrentSingerId: 'app/setCurrentSingerId',
      setSongSheetList: 'app/setSongSheetList',
      setSongOrderList: 'app/setSongOrderList',
    }),
    showAniStart() {
      this.isShowAni = true;
    },
    hideAniStart() {
      this.isShowAni = false;
    },
    openPopupModule(e) {
      this.togglePopup();
      timeoutTask(() => {
        this.togglePopup(e.key);
      }, 200);
    },
    chooseNav(p) {
      this.navIndex = p.navIndex;
    },
    closePopupModule() {
      if (this.musicMode === '1') {
        // In singer mode, go back to the singer list.
        this.togglePopup(this.chooseSingerModuleKey);
      } else {
        // In normal mode, close the popup.
        this.hideAniStart();
        timeoutTask(() => {
          this.togglePopup();
        }, 200);
      }
    },
    async fetchInitialData() {
      try {
        if (this.musicMode === '1') {
          // 歌手模式：获取歌手列表
          //   const singerRes = await getSingerList();
          //   const singerList = singerRes.singerList || [];
          //   this.setSingerList(singerList);
          //   if (singerList.length > 0) {
          //     // 检查当前选中的歌手是否还存在
          //     const currentExists = this.currentSingerId && singerList.some((s) => s.awardid === this.currentSingerId);
          //     if (!this.currentSingerId || !currentExists) {
          //       // 首次加载或选中的歌手已不存在，选择第一个歌手
          //       const firstSingerId = singerList[0].awardid;
          //       await this.handleSelectSinger({ singerId: firstSingerId });
          //     } else {
          //       // 恢复之前选中的歌手，刷新其歌曲列表和已点列表
          //       const singerId = this.currentSingerId;
          //       this.setCurrentSingerId(''); // 临时重置以触发请求
          //       await this.handleSelectSinger({ singerId });
          //       // 数据加载完成后滚动到当前选中歌手的位置
          //       await this.$nextTick();
          //       if (this.currentSingerIndex !== -1) {
          //         this.scrollToSinger(this.currentSingerIndex);
          //       }
          //     }
          //   }
        } else {
          // 非歌手模式：获取全部歌曲列表和已点列表
          const songRes = await getSongSheetList('');
          this.setSongSheetList(songRes.list || []);
          this.fetchOrderedSongList('');
        }
      } catch (err) {
        console.error('Failed to fetch initial song data:', err);
      }
    },
    async handleSelectSinger(p) {
      const { singerId } = p;
      // 如果已经是当前选中的歌手，不重复请求
      if (this.currentSingerId === singerId) return;
      this.setCurrentSingerId(singerId);
      try {
        const songRes = await getSongSheetList(singerId);
        this.setSongSheetList(songRes.list || []);
        // 切换歌手后，根据当前歌手ID刷新已点列表
        this.fetchOrderedSongList(singerId);
      } catch (err) {
        console.error(`Failed to fetch songs for singer ${singerId}:`, err);
      }
    },
    handleChooseSong(p) {
      const { song } = p;
      this.songToOrder = song;
      this.isConfirmModalVisible = true;
    },
    closeModal() {
      this.isConfirmModalVisible = false;
      this.songToOrder = null;
      this.form = { deskNum: '', blessing: '' };
    },
    getTmpBless() {
      const randomIndex = Math.floor(Math.random() * BLESSING_LIST.length);
      this.form.blessing = BLESSING_LIST[randomIndex];
    },
    confirmAndPay() {
      if (!this.form.deskNum) {
        this.$toast.center('请输入您的桌号!');
        return;
      }
      if (!this.form.blessing) {
        this.$toast.center('请输入您的祝福语!');
        return;
      }
       // 取消回调模式后不需要恢复的逻辑 因为当前页面状态不会丢失 所以以下两行代码注释
      // localStorage.setItem('tmpSongId', this.songToOrder.id);
      // localStorage.setItem('tmpSongName', this.songToOrder.name);
     // localStorage.setItem('tmpOrderForm', JSON.stringify(this.form));
      // 保存点歌模式和歌手ID，用于支付返回后恢复正确的弹窗
      // localStorage.setItem('tmpMusicMode', this.musicMode);
      // localStorage.setItem('tmpSingerId', this.$store.state.app.currentSingerId);
      this.setOrigin('orderSong');
      wx.miniProgram.navigateTo({
        url: `/pages/pay/pay?openId=${this.$store.state.user.openId}&userId=${this.$store.state.user.userId}&total=${this.songToOrder.price}&origin=${this.$store.state.app.origin}&orderSongFormJson=${JSON.stringify(this.form)}&songId=${this.songToOrder.id}`,
      });
      this.closeModal();
    },
    fetchOrderedSongList(singerId = '') {
      getSongOrderedList(singerId)
        .then((res) => {
          this.setSongOrderList(res.list || []);
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // START: 新增方法
    // 滚动到指定索引的歌手位置
    scrollToSinger(index) {
      const carousel = this.$refs.singerCarousel;
      if (carousel && carousel.children[index]) {
        const item = carousel.children[index];
        // 计算目标滚动位置，使其大致居中
        const scrollLeft = item.offsetLeft - carousel.offsetWidth / 2 + item.offsetWidth / 2;
        carousel.scrollTo({ left: scrollLeft, behavior: 'smooth' });
      }
    },
    // 处理左右箭头点击事件
    navigate(p) {
      const { direction } = p;
      let newIndex = this.currentSingerIndex + direction;
      // 循环切换
      if (newIndex < 0) {
        newIndex = this.singerList.length - 1;
      } else if (newIndex >= this.singerList.length) {
        newIndex = 0;
      }
      const nextSinger = this.singerList[newIndex];
      if (nextSinger) {
        this.handleSelectSinger({ singerId: nextSinger.awardid });
      }
    },
    // END: 新增方法
  },
};
</script>
<style lang="less" scoped>
.chooseSongModule {
  position: absolute;
  width: 100%;
  bottom: 0;
  .chooseSongBox {
    width: 750px;
    height: 97vh;
    background-image: url('../../assets/image/popupArea/chooseSongBg.png');
    background-size: 100% 100%;
    flex-direction: column;
    position: relative;
    padding-bottom: 40px;
    .closeIcon {
      width: 48px;
      height: 48px;
      position: absolute;
      right: 16px;
      top: 4px;
    }
    .chooseSongTitle {
      width: 342px;
      height: 72px;
    }
    .singer-name-wrapper {
      height: 72px;
      max-width: calc(100% - 80px); /* 预留右侧关闭按钮空间 */
      min-width: 342px;
      padding: 0 32px;
      box-sizing: border-box;
      background-image: url('../../assets/image/container/singer-bg.png');
      background-size: 100% 100%;
      background-repeat: no-repeat;
      background-position: center;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 40px;
      color: #ffffff;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .nav {
      justify-content: space-around;
      width: 100%;
      margin-top: 40px;
      .navItem {
        font-size: 28px;
        font-weight: 400;
        color: rgba(255, 255, 255, 0.6);
        flex-direction: column;
        &.active {
          color: #fff;
          &::after {
            display: block;
            content: '';
            width: 32px;
            height: 4px;
            background: #ffffff;
            border-radius: 20px;
            margin-top: 4px;
          }
        }
      }
    }
    // 歌曲列表 / 已点列表 公用样式
    .songSheetWrap,
    .playSheetWrap {
      width: 100%;
      flex: 1;         // 关键：占满剩余空间
      min-height: 0;   // 关键：允许内部滚动
      overflow-y: auto;
      margin-top: 32px;
    }
    .songSheetWrap {
      .songItem {
        width: 686px;
        height: 136px;
        background: #3c2183;
        border-radius: 16px;
        margin: 0 auto;
        margin-bottom: 16px;
        padding: 20px 32px;
        position: relative;
        .info {
          margin-left: 32px;
          .songName {
            width: 63vw;
            font-size: 32px;
            font-weight: 400;
            color: #c2baf5;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          .chooseNum {
            font-size: 28px;
            font-weight: 400;
            color: #c2baf5;
            margin-top: 8px;
          }
        }
        .price {
          font-size: 32px;
          color: #c2baf5;
          position: absolute;
          right: 32px;
        }
      }
    }
    .playSheetWrap {
      .songItem {
        width: 686px;
        height: 110px;
        background: #3c2183;
        border-radius: 16px;
        margin: 0 auto;
        margin-bottom: 16px;
        padding: 20px 32px;
        position: relative;
        .songName {
          width: 63vw;
          font-size: 32px;
          font-weight: 400;
          color: #c2baf5;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .userInfo {
          flex-direction: column;
          position: absolute;
          right: 32px;
          .headImg {
            width: 60px;
            height: 60px;
            border-radius: 50%;
          }
          .userName {
            font-size: 21px;
            font-weight: 400;
            color: #c2baf5;
            margin-top: 4px;
            width: 20vw;
            text-align: center;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
    }
  }
}
/* --- START: 轮播区域全新样式 (修正版) --- */
.singer-carousel-container {
  width: 100%;
  position: relative; /* 为箭头绝对定位提供基准 */
  margin-top: 20px;
}
.arrow {
  /* 改为绝对定位，覆盖在轮播图之上 */
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
  width: 44px;
  height: 44px;
  background-color: rgba(0, 0, 0, 0.3); /* 增加背景色以提高可见性 */
  border-radius: 50%;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  /* 当歌手数量不足时隐藏箭头 */
  &.is-disabled {
    display: none;
  }
  &::after {
    content: '';
    display: block;
    width: 12px;
    height: 12px;
    border-style: solid;
    border-color: white;
    border-width: 0 2px 2px 0;
  }
  &.left-arrow {
    left: 32px; /* 距离左侧边缘的距离 */
    &::after {
      transform: translateX(2px) rotate(135deg);
    }
  }
  &.right-arrow {
    right: 32px; /* 距离右侧边缘的距离 */
    &::after {
      transform: translateX(-2px) rotate(-45deg);
    }
  }
}
.singer-carousel-wrapper {
  /* 宽度占满父容器，作为可视区域 */
  width: 100%;
  overflow: hidden;
}
.singer-carousel {
  display: flex;
  align-items: center;
  overflow-x: auto;
  /* 隐藏滚动条 */
  -ms-overflow-style: none;
  scrollbar-width: none;
  &::-webkit-scrollbar {
    display: none;
  }
  /*
    关键点：设置左右 padding 以便第一张和最后一张卡片能居中。
    计算公式: (容器宽度 - 卡片宽度) / 2
    容器宽度为 750px，卡片为 400px，则 padding = (750 - 400) / 2 = 175px
    这个 padding 确保了滚动到两端时，首尾卡片也能居中。
  */
  padding: 20px 175px;
}
.singer-item {
  position: relative;
  flex-shrink: 0; /* 防止项目在 flex 布局中被压缩 */
  width: 400px;
  height: 300px;
  margin: 0 14px; /* 项目间距为 28px */
  border-radius: 14px;
  overflow: hidden; /* 确保图片圆角生效 */
  .singer-image {
    width: 100%;
    height: 100%;
    object-fit: cover; /* 保证图片不变形地填满容器 */
    display: block;
  }
  .tick-icon {
    position: absolute;
    bottom: 16px;
    right: 16px;
    width: 48px;
    height: 48px;
  }
}
.pagination-dots {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 20px;
  .dot {
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background-color: #ffffff;
    margin: 0 8px; /* 点之间的间距 */
    transition: background-color 0.3s;
    &.active {
      background-color: #dd01ff;
    }
  }
}
.singer-intro-box {
  margin-top: 28px; /* 与分页器的间距 */
  display: flex;
  justify-content: center;
}
.singer-intro {
  display: inline-block;
  padding: 11px 28px;
  border: 1px solid #c7b7fe;
  border-radius: 14px;
  font-size: 22px;
  color: #c7b7fe;
  text-align: center;
  min-height: 1.5em; /* 防止没名字时塌陷 */
}
/* --- END: 轮播区域全新样式 (修正版) --- */
/* --- 确认弹窗样式 (保持不变) --- */
.order-confirm-dialog-wrap {
  position: fixed;
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  z-index: 100;
  .shade {
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background-color: rgba(0, 0, 0, 0.6);
  }
  .dialog-content {
    flex-direction: column;
    width: 560px;
    padding: 32px 0;
    box-sizing: border-box;
    background-color: #fff;
    border-radius: 24px;
    position: relative;
    z-index: 1;
    padding-top: 48px;
    .dialog-title {
      font-size: 32px;
      margin-bottom: 34px;
      font-weight: bold;
      color: #333;
    }
    .info-item {
      font-size: 28px;
      color: #666;
      margin-bottom: 16px;
      .price {
        color: #ff3675;
        font-weight: 500;
      }
    }
    .form-item {
      padding: 0 24px;
      margin: 20px 0;
      width: 100%;
      .form-key {
        font-size: 28px;
        font-weight: 500;
        margin-bottom: 16px;
        text-align: left;
      }
      .form-val {
        .dialog-input {
          width: 100%;
          height: 70px;
          padding: 24px;
          box-sizing: border-box;
          border-radius: 8px;
          border: 2px solid #d9d9d9;
          font-size: 28px;
        }
        &.bless-container {
          position: relative;
          .bless-txtarea {
            width: 100%;
            height: 140px;
            padding: 16px 110px 16px 24px;
            box-sizing: border-box;
            border: 2px solid #d9d9d9;
            border-radius: 8px;
            font-size: 28px;
            resize: none;
          }
          .yulu-btn {
            padding: 10px 16px;
            box-sizing: border-box;
            background-color: #f0f0f0;
            border-radius: 10px;
            color: #666;
            font-size: 24px;
            position: absolute;
            top: 16px;
            right: 24px;
          }
        }
      }
    }
    .pay-btn {
      margin-top: 30px;
      width: 512px;
      height: 80px;
      background: linear-gradient(90deg, #6c47ff, #ff68f9 100%);
      border-radius: 12px;
      font-size: 28px;
      font-weight: 500;
      color: #ffffff;
    }
    .cancel-btn {
      margin-top: 30px;
      font-size: 28px;
      font-weight: 400;
      color: #999;
    }
  }
}
</style>
